<?php

namespace app\admin\controller;

use app\library\upload\Upload;
use app\model\AdminMenuModel;
use app\model\AdminModel;
use app\model\AdminOptionModel;
use app\model\AdminRolesModel;
use Carbon\Carbon;
use Shopwwi\LaravelCache\Cache;
use support\Redis;
use support\Request;

class IndexController
{
    //获取后台登录首页统计数据
    public function getDashboardData(){

        $data = [
            'request_pv_total'=>Cache::get('request_pv_total',0),
            'request_pv_day'=>Cache::get('request_pv_'.date('Y_m_d')),
            'cpu_count'=>cpu_count(),
            'start_server'=>config('server.count'),
        ];
        return success("ok",$data);
    }

    //获取后台首页系统信息
    public function getSystemInfo(){

        //$os
        $os = PHP_OS;

        $mysql = \think\facade\Db::query('SELECT VERSION() as mysql_version')[0]['mysql_version'];

        //返回redis信息
        $handler = Redis::connection('default');
        $redis = $handler->info();

        //获取当前db的key总量
        $dbinfo = $redis['db'.getenv('RDS_DATABASE')];
        $keys = end(explode("=",explode(",",$dbinfo)[0]));
        $redis['keycount'] = $keys;

        $data = [
            'os'=>$os,
            'mysql'=>$mysql,
            'redis'=>$redis,
        ];

        $data = [
            [
                'key'=>'服务器版本',
                'value'=>php_uname("s").' '.php_uname("m")
            ],
            [
                'key'=>'PHP Version',
                'value'=>PHP_VERSION
            ],
            [
                'key'=>'Mysql Version',
                'value'=>$mysql
            ],
            [
                'key'=>'default timezone',
                'value'=>config('app.default_timezone')
            ],
            [
                'key'=>'Redis Version',
                'value'=>$redis['redis_version']
            ],
            [
                'key'=>'Redis 使用内存',
                'value'=>$redis['used_memory_human']
            ],
            [
                'key'=>'Redis db '.getenv('RDS_DATABASE').' key总量',
                'value'=>$keys
            ],
            
        ];

        return success("ok",$data);
    }

    //获取后台登录首页最近请求量列表数据
    public function getDashboardPvList(Request $request)
    {
        $days = $request->input("days");

        // 获取当前时间
        $endDate = Carbon::now();

        // 获取开始日期，确保包括今天
        $startDate = $endDate->copy()->subDays($days - 1); // 减去 (days - 1) 天，这样包括今天

        // 初始化日期数组和请求量数组
        $dateArray = [];
        $requestArray = [];

        // 循环生成日期并从缓存中获取请求量
        for ($i = 0; $i < $days; $i++) {
            // 获取日期
            $date = $startDate->copy()->addDays($i)->format('Y_m_d');
            
            // 获取该日期的请求量，默认值为0
            $requestCount = Cache::get('request_pv_' . $date, 0);  

            // 将日期和请求量添加到数组中
            $dateArray[] = $startDate->copy()->addDays($i)->format('Y-m-d');
            $requestArray[] = $requestCount;
        }

        // 返回成功响应，包含日期和请求量数组
        return success("ok", ['days' => $dateArray, 'values' => $requestArray]);
    }
    
    //获取当前管理员信息
    public function getInfo(Request $request){

        $detail = AdminModel::withoutField('password')->find($request->adminid);

        return success("ok",['detail'=>$detail]);
    }

    //系统设置提交
    public function postSetting(Request $request){

        $all = $request->all();

        $option_name = $all['option_name'];

        if(empty($option_name) || !in_array($option_name,['setting','system','config','upload'])) return error('参数错误');

        unset($all['option_name']);

        $option = AdminOptionModel::where("option_name",$option_name)->findOrEmpty();

        $option->option_name = $option_name;
        $option->option_value = le_json($all);
        $option->save();

        return success("保存成功");
    }

    //获取系统设置
    public function getSetting(Request $request){

        $option_name = $request->input("option_name",'setting');

        $option = AdminOptionModel::where("option_name",$option_name)->find();

        if(empty($option['option_value'])){
            return success("ok",[]);
        }else{
            return success("ok",json_decode($option['option_value'],true));
        }

    }

    //获取当前角色菜单列表
    public function getMenu(Request $request){

        $menu_ids = AdminRolesModel::getAdminMenu($request->adminid);

        if(in_array('*',$menu_ids)){
            $list = AdminMenuModel::where("type",1)
            ->order("sort asc")->column('id,pid,menu_type,title,name,icon,component,path,sort,more,isshow','id');
        }else{
            $list = AdminMenuModel::where("id",'in',$menu_ids)
            ->where("type",1)
            ->order("sort asc")->column('id,pid,menu_type,title,name,icon,component,path,sort,more,isshow','id');
        }

        //处理子级
        $newlist = [];
        foreach($list as $k=>$v){
            // if(!empty($v['more'])){
            //     $list[$k]['more'] = json_decode($v['more'],true);
            // }else{
            //     $list[$k]['more'] = '';
            // }
            $list[$k]['more'] = json_decode($v['more'],true);
            if($v['pid'] && $list[$v['pid']]){
                //处理上级
                $list[$v['pid']]['children'][] = &$list[$k];
            }else{
                $newlist[] = &$list[$k];
            }
        }

        return success("ok",$newlist);
    }

    //获取所有菜单/权限列表
    public function getAllMenu(Request $request){

        $list = AdminMenuModel::order("sort asc")->column('*','id');

        $newlist = [];

        foreach($list as $k=>$v){

            //$list[$k]['more'] = json_decode($v['more'],true);
            if($v['pid'] && $list[$v['pid']]){
                //处理上级
                $list[$v['pid']]['children'][] = &$list[$k];
            }else{
                $newlist[] = &$list[$k];
            }
        }

        return success("ok",$newlist);
    }

    //获取某个菜单详情
    public function getMenuDetail(Request $request){

        $id = $request->input("id");

        $detail = AdminMenuModel::find($id);

        if(empty($detail)){
            return error("菜单不存在");
        }

        return success("ok",$detail);
    }

    //添加/编辑菜单
    public function postMenu(Request $request){

        $all = $request->all();

        if(empty($all['title'])){
            return error("请输入菜单标题");
        }

        if(!empty($all['id'])){
            //编辑
            if($all['id'] == $all['pid']){
                return error("上级菜单不能为自己");
            }

            AdminMenuModel::where("id",$all['id'])->update($all);

        }else{
            //添加
            AdminMenuModel::create($all);
        }

        return success("操作成功");
    }

    //删除菜单
    public function delMenu(Request $request){

        $id = $request->input("id");

        if(empty($id)) return error("参数错误");

        if(!empty(AdminMenuModel::where("pid",$id)->find())){
            return error("请先删除下级菜单");
        }

        $detail = AdminMenuModel::find($id);

        if(empty($detail)){
            return error("菜单不存在");
        }

        $detail->delete();

        return success("删除成功");
    }

    //获取角色列表
    public function getRolesList(Request $request){

        $all = $request->all();

        $list = AdminRolesModel::getList($all);

        return success("ok",$list);
    }

    //获取某个角色详情
    public function getRolesDetail(Request $request){

        $id = $request->input("id");

        $detail = AdminRolesModel::find($id);

        if(empty($detail)){
            return error("角色不存在");
        }

        return success("ok",$detail);
    }

    //添加/编辑角色
    public function postRoles(Request $request){

        $all = $request->all();

        if($all['id'] == '1'){
            return error("无法编辑超级管理员");
        }

        if(empty($all['name'])) return error("请输入角色名称");
        
        $menu_ids = [];
        if(!empty($all['menu_ids'])){
            $menu_ids = implode(",",$all['menu_ids']);
        }

        $detail = AdminRolesModel::where("id",$all['id'])->findOrEmpty();
        $detail->name = $all['name'];
        $detail->menu_ids = $menu_ids;
        $detail->save();

        return success("操作成功");
    }

    //删除角色
    public function delRoles(Request $request){

        $id = $request->input("id");

        if($id == '1'){
            return error("无法删除超级管理员");
        }

        $detail = AdminRolesModel::find($id);

        if(empty($detail)){
            return error("角色不存在");
        }

        $detail->delete();

        return success("删除成功");
    }

    //获取所有角色
    public function getAllRoles(Request $request){
        $list = AdminRolesModel::select();

        return success("ok",$list);
    }

    //管理员管理
    public function getAdminList(Request $request){
        $all = $request->all();

        $list = AdminModel::getList($all);

        return success("ok",$list);
    }

    //获取管理员详情
    public function getAdminDetail(Request $request){

        $id = $request->input("id");

        $detail = AdminModel::find($id);

        if(empty($id) || empty($detail)) return error("获取失败");

        return success("ok",$detail);
    }

    //添加/编辑管理员
    public function postAdmin(Request $request){

        $all = $request->all();

        if ($all['id'] == 1) return error('无法编辑admin用户');

        $roles = '';
        if(!empty($all['roles'])){
            $roles = trim(implode(",", $all['roles']), ",");
        }

        $password = '';
        if (!empty($all['password'])) {
            $password = get_password($all['password']);
        }

        $where = [
            ['username', '=', $all['username']],
        ];

        if (!empty($all['id'])) $where[] = ['id', '<>', $all['id']];

        if (!empty(AdminModel::where($where)->value("id"))) {
            return error('账号重复');
        }

        $detail = AdminModel::where("id",$all['id'])->findOrEmpty();
        $detail->username = $all['username'];
        $detail->roles = $roles;
        if(!empty($password)){
            $detail->password = $password;
        }
        $detail->save();

        return success("操作成功");
    }

    //删除管理员
    public function delAdmin(Request $request){

        $id = $request->input("id");

        if($id == $request->adminid){
            return error("无法删除自己");
        }

        if($id == 1){
            return error("无法删除admin");
        }

        $detail = AdminModel::find($id);

        if(empty($detail)){
            return error("管理员不存在");
        }

        $detail->delete();

        return success("删除成功");

    }

    //修改密码
    public function changePassword(Request $request){

        $password = $request->input("password");

        if(empty($password)){
            return error("请输入密码");
        }

        $detail = AdminModel::find($request->adminid);
        $detail->password = get_password($password);
        $detail->save();

        return success("修改成功");
    }

    //后台文件上传
    public function upload(Request $request){

        $upload = new Upload();

        try{
            $res = $upload->upload($request->file());
        }catch(\Throwable $throwable){

            return error($throwable->getMessage());
        }

        return success('ok',$res);
    }

    //退出登录
    public function logout(Request $request){

        Cache::tags('admin')->pull('token_'.$request->token);

        return success("退出成功");
    }

}
